package ui;

import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import util.CapsJdbc;
import util.CapsRes;
import util.CapsTableView;

import java.net.URL;
import java.util.*;

public class RoomMgr implements Initializable {

   @FXML
   private TextField rno;

   @FXML
   private TextField capacity;

   @FXML
   private TextField flag;
   
   @FXML
   private TextField remark;
   
   @FXML
   private TextField roomCond;

   @FXML
   private TableView<Map<String,String>> roomTv;

   @FXML
   private void saveRoom(ActionEvent event) {
      List<Object> params = new ArrayList<>(Arrays.asList(capacity.getText(),flag.getText(),remark.getText(),rno.getText()));
      String updSql = "update room set capacity=?,flag=?,remark=? where rno=?";
      CapsRes capsRes = CapsJdbc.execSQL(updSql,params);
      if (capsRes.getTtlNum() < 1) {
         String addSql = "insert into room(capacity,flag,remark,rno) values(?,?,?,?)";
         CapsJdbc.execSQL(addSql,params);
      }
      this.qryByRoom(null);
   }
   
   @FXML
   private void qryByRoom(ActionEvent event) {
      this.dealQry(roomCond.getText());
   }

   @Override
   public void initialize(URL url, ResourceBundle rb) {
//      deptTv.getSelectionModel().selectedItemProperty()
//              .addListener((observable,  oldValue, newValue) -> {
//
////                 System.out.println("observable:"+observable.getValue()+";oldValue:"+oldValue
////                         +";newValue:"+newValue);
//              });
      this.dealQry(null);
   }

   private void dealQry(String roomNum) {
      roomTv.setItems(null);
      roomTv.getColumns().clear();
      String strSQL = "select rno,capacity,flag,remark from room";
      List<Object> params = null;
      if (null != roomNum && roomNum.length() > 0) {
         strSQL += " where rno like ?";
         params = new ArrayList<>(1);
         params.add(roomNum+"%");
      }
      CapsRes capsRes = CapsJdbc.execSQL(strSQL,params);
      CapsTableView.dealTableView(capsRes,roomTv);
      CapsTableView.addButtonToTable(roomTv,(recMap,idCol) -> {
         String delSql = "delete from room where rno = ?";
         List<Object> delParams = new ArrayList<>(1);
         delParams.add(recMap.get("rno"));
         CapsJdbc.execSQL(delSql,delParams);
         this.dealQry(null);
      },(recMap,idCol) -> {
           rno.setText(recMap.get("rno"));
           capacity.setText(recMap.get("capacity"));
           flag.setText(recMap.get("flag"));
           remark.setText(recMap.get("remark"));
      });
   }
}
